package com.hcb.fragment;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.hcb.app911.MainActivity;
import com.hcb.app911.R;
import com.hcb.constants.Constants;
import com.hcb.dto.AlertDTO;
import com.hcb.dto.ResponderListDTO;
import com.hcb.webservice.CustomMultiPartEntity;
import com.hcb.webservice.InternetUtils;
import com.hcb.webservice.ServiceHandler;
import com.hcb.webservice.ServiceHandlerUpload;
import com.hcb.webservice.CustomMultiPartEntity.ProgressListener;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Video;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class UpdateAlertFragment extends Fragment implements OnClickListener {
	Button btnSendAlertUpdate, btnPhoto, btnAudio;
	
	// final private int PICK_IMAGE = 1;
	private String imgPath;
	String alert_id;
	public static EditText edAddingNotes;
	public static ImageView imgAlert, imgAlertVideo;
	public static String selectedImagePath = "";
	public static String selectedAudioPath = "";
	int serverResponseCode = 0;
	ProgressBar proupload;
	TextView txttotalSize;
	public static String addNotes = "";

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_update_alert,
				container, false);
		((MainActivity)this.getActivity()).getImgDetail().setImageResource(R.drawable.mydetail);
		((MainActivity)this.getActivity()).getImgHome().setImageResource(R.drawable.icon);
		Bundle data = getArguments();
//		Bundle data = getIntent().getExtras();
		if (data != null)
			alert_id = data.getString("alert_id");
		btnSendAlertUpdate = (Button) rootView
				.findViewById(R.id.btnSendAlertUpdate);

		btnPhoto = (Button) rootView.findViewById(R.id.btnPhoto);

		btnAudio = (Button) rootView.findViewById(R.id.btnAudio);
		btnPhoto.setOnClickListener(this);
		btnAudio.setOnClickListener(this);
		btnSendAlertUpdate.setOnClickListener(this);
		edAddingNotes = (EditText) rootView.findViewById(R.id.edAddingNotes);
		imgAlert = (ImageView) rootView.findViewById(R.id.imgAlert);
		imgAlertVideo = (ImageView) rootView.findViewById(R.id.imgAlertVideo);
		proupload = (ProgressBar) rootView.findViewById(R.id.proupload);
		txttotalSize = (TextView) rootView.findViewById(R.id.txttotalSize);
		return rootView;
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		Intent intent = null;
		switch (id) {
		case R.id.btnSendAlertUpdate:
			if (InternetUtils.getInstance().isConnectingToInternet(
					getActivity())) {
				btnSendAlertUpdate
						.setBackgroundResource(R.drawable.updatealertf);
				addNotes = edAddingNotes.getText().toString();
				if (!addNotes.equalsIgnoreCase("")) {
					new VerySlowTaskAddNotes(alert_id).execute();
				}
				if (!selectedImagePath.equalsIgnoreCase("")) {
					new VerySlowTask(selectedImagePath, alert_id).execute();
				}
				if (!selectedAudioPath.equalsIgnoreCase("")) {
					proupload.setVisibility(View.VISIBLE);
					txttotalSize.setVisibility(View.VISIBLE);
					new VerySlowTaskAddAudio(selectedAudioPath, alert_id)
							.execute();

				}
				if (!addNotes.equalsIgnoreCase("")
						|| !selectedImagePath.equalsIgnoreCase("")
						|| !selectedAudioPath.equalsIgnoreCase("")) {

					ThankYouFragment fragment = new ThankYouFragment();
					FragmentManager fragmentManager = getActivity()
							.getSupportFragmentManager();
					FragmentTransaction ft = fragmentManager.beginTransaction();

					if (fragment != null) {
						ft.remove(fragment);
						ft.replace(R.id.frame_container, fragment);
						ft.addToBackStack("abc");
						ft.commit();
					}

					// intent = new Intent(UpdateAlertActivity.this,
					// ThankYouActivity.class);
					// startActivity(intent);
				} else {
					Toast.makeText(getActivity(), "Please choose alert",
							Toast.LENGTH_LONG).show();
					btnSendAlertUpdate
							.setBackgroundResource(R.drawable.updatealert);
				}
			} else {
				Toast.makeText(getActivity(),
						"No network please connect network", Toast.LENGTH_LONG)
						.show();
			}

			break;
		case R.id.btnPhoto:
			// File tempFolder = new
			// File(Environment.getExternalStorageDirectory().getAbsolutePath()
			// + "/myfolder");
			// tempFolder.mkdir();
			// File file = new
			// File(Environment.getExternalStorageDirectory().getAbsolutePath()
			// + "/myfolder",
			// String.valueOf(System.currentTimeMillis()) + ".jpg");
			// Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			// intent1.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
			// startActivityForResult(intent1, CAPTURE_RETURN);

			// intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			// intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
			// startActivityForResult(intent, CAPTURE_IMAGE);
			btnPhoto.setBackgroundResource(R.drawable.photof);
			intent = new Intent(Intent.ACTION_PICK);
			intent.setType("image/*");
			intent.setAction(Intent.ACTION_GET_CONTENT);
			startActivityForResult(
					Intent.createChooser(intent, "Select Picture"),
					Constants.CAPTURE_RETURN);
			break;
		case R.id.btnAudio:
			btnAudio.setBackgroundResource(R.drawable.audiof);
			intent = new Intent(Intent.ACTION_PICK);
			intent.setType("video/*");
			intent.setAction(Intent.ACTION_GET_CONTENT);
			startActivityForResult(
					Intent.createChooser(intent, "Select Video"),
					Constants.REQUESTCODE_RECORDING);
			break;

		default:
			break;
		}

	}
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		AlertDTO alert = new AlertDTO();

		switch (requestCode) {
		case Constants.CAPTURE_RETURN:
			if (resultCode == Activity.RESULT_OK) {
				btnPhoto.setBackgroundResource(R.drawable.photo);
				Uri selectedImageUri = data.getData();
				selectedImagePath = getPath(selectedImageUri);
				imgAlert.setImageBitmap(decodeFile(selectedImagePath));
			}
			break;
		case Constants.REQUESTCODE_RECORDING:

			if (resultCode == Activity.RESULT_OK) {
				btnAudio.setBackgroundResource(R.drawable.audio);
				Uri videoUri = data.getData();
				selectedAudioPath = getPath(videoUri);
				Cursor cursor = getActivity().managedQuery(videoUri, null, null, null,
						null);
				if (cursor.moveToFirst()) {

					long id = cursor.getLong(cursor
							.getColumnIndex(Video.VideoColumns._ID));
					ContentResolver crThumb = getActivity().getContentResolver();
					BitmapFactory.Options options = new BitmapFactory.Options();
					options.inSampleSize = 1;
					Bitmap curThumb = MediaStore.Video.Thumbnails.getThumbnail(
							crThumb, id,
							MediaStore.Video.Thumbnails.MICRO_KIND, options);
					imgAlertVideo.setImageBitmap(curThumb);
				}

			}
			break;
		}
	}
	public Bitmap decodeFile(String path) {
		try {
			// Decode image size
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(path, o);
			// The new size we want to scale to
			final int REQUIRED_SIZE = 70;

			// Find the correct scale value. It should be the power of 2.
			int scale = 1;
			while (o.outWidth / scale / 2 >= REQUIRED_SIZE
					&& o.outHeight / scale / 2 >= REQUIRED_SIZE)
				scale *= 2;

			// Decode with inSampleSize
			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			return BitmapFactory.decodeFile(path, o2);
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return null;

	}
	public String getPath(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}
	public Uri setImageUri() {
		// Store image in dcim
		File file = new File(Environment.getExternalStorageDirectory()
				+ "/DCIM/", "image" + new Date().getTime() + ".png");
		Uri imgUri = Uri.fromFile(file);
		this.imgPath = file.getAbsolutePath();
		return imgUri;
	}

	public String getImagePath() {
		return imgPath;
	}

	public class SendImageHttpPost {
		public static final String TAG = "SendImageHttpPost";

		public void sendPost(String url, String imagePath) throws IOException,
				ClientProtocolException {
			HttpClient httpclient = new DefaultHttpClient();
			httpclient.getParams().setParameter(
					CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

			HttpPost httppost = new HttpPost(url);
			File file = new File(imagePath);
			FileBody fb = new FileBody(file);

			// MultipartEntityBuilder builder = MultipartEntityBuilder.create();
			// builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
			//
			// builder.addPart("userfile", fb);
			// final HttpEntity entity = builder.build();

			// httppost.setEntity(entity);
			Log.i(TAG, "Executing request: " + httppost.getRequestLine());
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity resEntity = response.getEntity();
			Log.i(TAG, "" + response.getStatusLine());
			if (resEntity != null) {
				Log.i(TAG, EntityUtils.toString(resEntity));
			}
			if (resEntity != null) {
				resEntity.consumeContent();
			}
			httpclient.getConnectionManager().shutdown();
		}
	}

	public class VerySlowTask extends AsyncTask<Void, Void, Void> {
		// String result;
		// CustomerDTO customer;
		//
		// public VerySlowTask(CustomerDTO cus) {
		// customer = cus;
		// }
		String pathImg = "";
		String _alert_id = "";

		public VerySlowTask(String selectedImagePath, String alert_id) {
			pathImg = selectedImagePath;
			_alert_id = alert_id;
		}

		@Override
		protected Void doInBackground(Void... params) {

			ServiceHandlerUpload sh = new ServiceHandlerUpload();
			File file = new File(selectedImagePath);
			String jsonStr = sh.uploadService(pathImg, _alert_id);
			if (jsonStr != null) {
				try {
					JSONObject object;
					object = new JSONObject(jsonStr);
					String value = object.getString("result");
					if (value.contains("success")) {

					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {

			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);

		}

	}

	public class VerySlowTaskAddNotes extends AsyncTask<Void, Void, Void> {
		// String result;
		// CustomerDTO customer;
		//
		// public VerySlowTask(CustomerDTO cus) {
		// customer = cus;
		// }
		String _alert_id = "";

		public VerySlowTaskAddNotes(String alert_id) {
			_alert_id = alert_id;
		}

		@Override
		protected Void doInBackground(Void... params) {

			ServiceHandler sh = new ServiceHandler();
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("query",
					Constants.UPDATE_ADDITIONAL_NOTES));
			nameValuePairs.add(new BasicNameValuePair("api_secret_key",
					Constants.API_KEY));
			nameValuePairs.add(new BasicNameValuePair("alert_id", _alert_id));

			nameValuePairs.add(new BasicNameValuePair(
					Constants.ADDITIONAL_NOTES, edAddingNotes.getText()
							.toString()));

			String jsonStr = sh.makeServiceCall(Constants.URL_SERVICE,
					ServiceHandler.POST, nameValuePairs);
			if (jsonStr != null) {
				try {
					JSONObject object;
					object = new JSONObject(jsonStr);
					String value = object.getString("result");
					if (value.contains("success")) {

						// ActionEvent e = new ActionEvent(
						// MainActivity.this,
						// Constants.INSERT_CUSTOMER_EXIST, customer, null);
						// CustomerController.getInstance().handleViewEvent(e);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				// Log.e("ServiceHandler",
				// "Couldn't get any data from the url");
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);

		}

	}

	public class VerySlowTaskAddAudio extends
			AsyncTask<HttpResponse, Integer, Void> {
		// ProgressDialog pd;
		long totalSize;
		private int progressStatus = 0;

		@Override
		protected void onPreExecute() {

			// proupload.showContextMenu();
			// proupload.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			//
			// pd = new ProgressDialog(UpdateAlertActivity.this);
			// pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			// pd.setMessage("Uploading Picture...");
			// pd.setCancelable(false);
			// pd.show();
		}

		String urlVideo = "";
		String _alert_id = "";

		public VerySlowTaskAddAudio(String selectedAudioPath, String alert_id) {
			urlVideo = selectedAudioPath;
			_alert_id = alert_id;
		}

		@Override
		protected Void doInBackground(HttpResponse... params) {

			while (progressStatus < 100) {
				progressStatus += 1;
				DefaultHttpClient httpclient = new DefaultHttpClient();
				HttpPost postRequest = new HttpPost(Constants.URL_SERVICE);
				HttpEntity httpEntity = null;
				try {

					CustomMultiPartEntity multipartContent = new CustomMultiPartEntity(
							new ProgressListener() {
								@Override
								public void transferred(long num) {
									publishProgress((int) ((num / (float) totalSize) * 100));
								}
							});
					// MultipartEntity reqEntity = new MultipartEntity();

					multipartContent.addPart("query", new StringBody(
							"fileTransfer"));
					multipartContent.addPart("alert_id", new StringBody(
							_alert_id));

					multipartContent.addPart("file_contents", new FileBody(
							new File(urlVideo)));
					multipartContent.addPart("api_secret_key", new StringBody(
							Constants.API_KEY));
					totalSize = multipartContent.getContentLength();
					postRequest.setEntity(multipartContent);

					HttpResponse response = httpclient.execute(postRequest);
					httpEntity = response.getEntity();
					String responsecontent = EntityUtils.toString(httpEntity);

				}

				catch (Exception e) {
					System.out.println(e);
				}
				// ServiceHandlerUpload sh = new ServiceHandlerUpload();
				// File file = new File(selectedImagePath);
				// String jsonStr = sh.uploadService(urlVideo, _alert_id);
				// if (jsonStr != null) {
				// try {
				// JSONObject object;
				// object = new JSONObject(jsonStr);
				// String value = object.getString("result");
				// if (value.contains("success")) {
				//
				// }
				// } catch (JSONException e) {
				// e.printStackTrace();
				// }
				// } else {
				//
				// }
			}
			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... progress) {
			proupload.setProgress((int) (progress[0]));
			progressStatus = (int) (progress[0]);
			proupload.setProgress(progressStatus);
			txttotalSize.setText((int) (progress[0]) + "%");
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			proupload.setVisibility(View.GONE);
			txttotalSize.setVisibility(View.GONE);

		}

	}
}
